package com.cqupt.scanning.system.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqupt.scanning.handler.exception.MyException;
import com.cqupt.scanning.system.acl.service.AclUserService;
import com.cqupt.scanning.system.admin.entity.*;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqupt.scanning.system.acl.entity.AclUser;
import com.cqupt.scanning.system.admin.entity.Department;

import com.cqupt.scanning.system.admin.mapper.DepartmentMapper;
import com.cqupt.scanning.system.admin.service.DepartmentService;
import com.cqupt.scanning.system.admin.service.DeviceFootService;
import com.cqupt.scanning.system.admin.service.DeviceThreeService;
import com.cqupt.scanning.system.utils.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 宋宝梁
 * @since 2021-07-06
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    private DeviceFootService deviceFootService;
    private DeviceThreeService deviceThreeService;
    private AclUserService aclUserService;

    @Autowired
    @Lazy
    public DepartmentServiceImpl(AclUserService aclUserService,DeviceFootService deviceFootService,DeviceThreeService deviceThreeService) {
        this.aclUserService = aclUserService;
        this.deviceFootService = deviceFootService;
        this.deviceThreeService = deviceThreeService;
    }

    @Override
    public R insert(Department department) {
        int id = baseMapper.insert(department);
        if (id <= 0) R.error().message("添加失败，请重新操作");
        return R.ok();
    }

    @Override
    public R update(Map<String,Object> dataMap) {

        String orgNum = JSONUtil.toJsonStr(dataMap.get("orgNum"));
        Object departmentObject= dataMap.get("departments");
        JSONArray mobileList = JSONUtil.parseArray(departmentObject);

        for(int i=0;i<mobileList.size();i++) {

            Department department = JSONUtil.toBean(JSONUtil.toJsonStr(mobileList.get(i)), Department.class);
            QueryWrapper<Department> department1 = new QueryWrapper<Department>().ne("id",department.getId());
            QueryWrapper<Department> department2 = department1.eq("org_num",orgNum);
            Integer count = baseMapper.selectCount(department2.eq("dep_name",department.getDepName()));
            if (count >= 1) {return R.error().message("在该医院所修改的科室重名");}
            department.setOrgNum(orgNum);
            int id = baseMapper.updateById(department);
            if (id <= 0) R.error().message("添加失败，请重新操作");
        }

        return R.ok();
    }

    @Override
    public R delById(Integer id) {
        try {
            Department department = baseMapper.selectOne(new QueryWrapper<Department>().eq("id", id));

            DeviceFoot deviceFoot = deviceFootService.getOne(new QueryWrapper<DeviceFoot>().eq("dep_id", department.getId()));
            List<DeviceFoot> deviceFootList = deviceFootService.list(new QueryWrapper<DeviceFoot>().eq("dep_id", department.getId()));
            List<Integer> footIds = deviceFootList.stream().map(DeviceFoot::getId).collect(Collectors.toList());
            List<Integer> userFootIds = deviceFootList.stream().map(DeviceFoot::getUserId).collect(Collectors.toList());

            DeviceThree deviceThree = deviceThreeService.getOne(new QueryWrapper<DeviceThree>().eq("dep_id", department.getId()));
            List<DeviceThree> deviceThreeList = deviceThreeService.list(new QueryWrapper<DeviceThree>().eq("dep_id", department.getId()));
            List<Integer> threeIds = deviceThreeList.stream().map(DeviceThree::getId).collect(Collectors.toList());
            List<Integer> userThreeIds = deviceThreeList.stream().map(DeviceThree::getUserId).collect(Collectors.toList());
            if (deviceFoot != null) {
                deviceFootService.removeByIds(footIds);
                aclUserService.removeByIds(userFootIds);
            }
            if (deviceThree != null) {
                deviceThreeService.removeByIds(threeIds);
                aclUserService.removeByIds(userThreeIds);
            }
            baseMapper.deleteById(id);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(20001, "Remove failed");
        }
    }
}
